package com.ribbon.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @BelongsProject: SpringCloudAlibabaLearn
 * @BelongsPackage: com.ribbon.rule
 * @Author: wang fei
 * @CreateTime: 2023-01-19  17:26
 * @Description: TODO 自定义规则，设置限流规则，自定义负载均衡策略
 * @Version: 1.0
 */
public class CustomRule extends AbstractLoadBalancerRule {
    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        //随机负载均衡策略

        ILoadBalancer loadBalancer = this.getLoadBalancer();

        //获取当前请求的服务实例
        List<Server> reachableServers = loadBalancer.getReachableServers();
        int random = ThreadLocalRandom.current().nextInt(reachableServers.size());
        Server server = reachableServers.get(random);
        if (server.isAlive()) {
            return null;
        }
        return server;
    }
}
